'''
this is the database package
it has many database utils

Created on 2010-11-23
@author: jadesoul
'''

from base import *
from mysql import *
from sqlserver import *
from sqllite import *

import re 


def dbgen(dburl="mysql://root:gbsoft@localhost:3306/dbname"):
	'''
	db generator
	'''
	s=dburl
	pos=dburl.find("://")
	if pos==-1: raise Exception("bad dburl: "+dburl)
	type=s[:pos]
	r=s[pos+3:]
	r=r.split("@")
	if len(r)!=2: raise Exception("bad dburl: "+dburl)
	l=r[0].split(":")
	if len(l)!=2: raise Exception("bad dburl: "+dburl)
	user=l[0]
	pwd=l[1]
	t=r[1].split("/")
	if len(t)!=2: raise Exception("bad dburl: "+dburl)
	db=t[1]
	r=t[0].split(":")
	host=r[0]
	port=int(r[1]) if len(r)==2 else None
	if type=="mysql":
		return mysql(host, user, pwd, db, port)
	elif type=="sqlserver":
		return None
	elif type=="sqllite":
		return None
	elif type=="access":
		return None
	elif type=="postprogress":
		return None
	else:
		raise Exception("bad db type")

def getdb(dburl="mysql://root:gbsoft@localhost:3306/dbname"):
	db=dbgen(dburl)
	db.connect()
	return db

def dbgen2(dburl="mysql://root:gbsoft@localhost:3306/dbname"):
	'''
	db generator v2
	'''
	r=re.compile("^(\w+)://(\w+):(\w+)@(\w+)(:(\d+))?/(\w+)$")
	m=r.findall(dburl)
	print m
	if len(m)!=1: raise Exception("bad dburl: "+dburl)
	(type, user, pwd, host, colon_port, port, db)=m[0]
	
	if type=="mysql":
		return mysql(host, user, pwd, db, port)
	elif type=="sqlserver":
		return None
	elif type=="sqllite":
		return None
	elif type=="access":
		return None
	elif type=="postprogress":
		return None
	else:
		raise Exception("bad db type")

		